<template>
  <div class="adsense-container">
    <div :id="adId" :data-ad-client="adClient" :data-ad-slot="adSlot" class="adsense-ad"></div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'

const props = defineProps({
  adClient: {
    type: String,
    default: 'ca-pub-8655046058014037'
  },
  adSlot: {
    type: String,
    required: true
  },
  adFormat: {
    type: String,
    default: 'auto'
  },
  responsive: {
    type: Boolean,
    default: true
  }
})

const adId = ref(`ad-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`)

onMounted(() => {
  // 确保AdSense脚本加载完成后再初始化广告
  if (typeof window !== 'undefined') {
    const initAd = () => {
      try {
        const adElement = document.getElementById(adId.value)
        if (adElement && window.adsbygoogle) {
          // 设置广告属性
          adElement.setAttribute('data-ad-format', props.adFormat)
          if (props.responsive) {
            adElement.setAttribute('data-full-width-responsive', 'true')
          }
          
          // 添加广告样式类
          adElement.className = 'adsbygoogle'
          adElement.style.display = 'block'
          
          // 推送广告
          window.adsbygoogle.push({})
        }
      } catch (error) {
        console.warn('AdSense initialization failed:', error)
      }
    }

    // 如果AdSense还没加载，等待加载
    if (!window.adsbygoogle) {
      const checkAdSense = setInterval(() => {
        if (window.adsbygoogle) {
          clearInterval(checkAdSense)
          initAd()
        }
      }, 100)
      
      // 10秒后停止检查
      setTimeout(() => clearInterval(checkAdSense), 10000)
    } else {
      initAd()
    }
  }
})
</script>

<style scoped>
.adsense-container {
  width: 100%;
  margin: 20px 0;
  text-align: center;
}

.adsense-ad {
  min-height: 100px;
  background-color: #f5f5f5;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
}

.adsense-ad::before {
  content: "广告位";
  color: #999;
  font-size: 12px;
}

/* 响应式广告样式 */
@media (max-width: 768px) {
  .adsense-ad {
    min-height: 80px;
  }
}
</style>